const fs = require('fs');
const { join } = require('path');
const Koa = require('koa');
const glob = require('tiny-glob/sync');

const build = require('./build');

const app = new Koa();

const appPath = join(__dirname, '..');

const indexHtml = fs.readFileSync(`${__dirname}/index.html`);
const indexJs = fs.readFileSync(`${__dirname}/index.js`);

// 错误处理
app.use(async (ctx, next) => {
  try {
    await next();
  } catch ({ status: code, message }) {
    ctx.status = code || 500;
    ctx.body = { code, message };
  }
});

// 静态页
app.use((ctx, next) => {
  if (ctx.path === '/') {
    ctx.type = 'html';
    ctx.body = indexHtml;
    return;
  }

  if (ctx.path === '/index.js') {
    ctx.type = 'js';
    ctx.body = indexJs;
    return;
  }

  return next();
});

// 文件列表
app.use((ctx, next) => {
  if (ctx.path !== '/api/files') {
    return next();
  }

  let tsfiles = [];
  let jsfiles = [];

  try {
    tsfiles = glob(`*.ts`, { cwd: `${appPath}/crawlers` });
  } catch ({ message }) {
    console.log(message);
  }

  try {
    jsfiles = glob(`*.js`, { cwd: `${appPath}/dist` });
  } catch ({ message }) {
    console.log(message);
  }

  const timeMap = {};

  // 从编译的文件中提取时间
  jsfiles.forEach(file => {
    const code = fs.readFileSync(`${appPath}/dist/${file}`, 'utf8');
    const [,appid] = code.match(/@appid ([^\r\n]+)/);
    const [,time] = code.match(/@time ([^\r\n]+)/);
    timeMap[appid] = time;
  });

  // 整理成最终数据
  const list = tsfiles.map(file => {
    const code = fs.readFileSync(`${appPath}/crawlers/${file}`, 'utf8');
    const [,name] = code.match(/@name ([^\r\n]+)/);
    const [,appid] = code.match(/@appid ([^\r\n]+)/);
    const time = timeMap[appid] || '';
    return { name, appid, file, time };
  });

  ctx.body = {
    code: 0,
    list
  };
});

// 编译
app.use(async (ctx, next) => {
  if (ctx.path !== '/api/build') {
    return next();
  }

  const { file } = ctx.query;
  const time = await build({ file });

  ctx.body = { code: 0, time};
});

// 发布
app.use((ctx, next) => {
  if (ctx.path !== '/api/release') {
    return next();
  }
  const { file } = ctx.query;
  ctx.body = { code: 0, file };
});

// 404
app.use((ctx) => {
  ctx.body = { code: 404 };
});

app.listen(8000, () => {
  console.log('http://localhost:8000');
});
